/**
 * @author franky.Fan
 * 秒表计时
 * */
package com.esdk.utils;

import com.esdk.esdk;

public class TimeMeter {
	private long begin=0,end=0;
	public TimeMeter() {
		begin();
	}

	public TimeMeter(Runnable runnable) {
		this();
		runnable.run();
		printElapse();
	}

	public TimeMeter(Runnable runnable,String template) {
		this();
		runnable.run();
		printElapse(template);
	}

	public TimeMeter begin() {
		this.begin=System.currentTimeMillis();
		return this;
	}

	public TimeMeter start() {
		return begin();
	}

	public TimeMeter end() {
		this.end=System.currentTimeMillis();
		return this;
	}

	public TimeMeter stop() {
		return end();
	}

	public long getElapse() {
		end=System.currentTimeMillis();
		return end-begin;
	}

	/**
	 * @param pattern: 耗时:{0}
	 * */
	public String getElapse(String pattern) {
		return EasyStr.format(pattern,EasyTime.formatElapse(getElapse()));
	}

	public String getHumanElapse() {
		return esdk.time.formatElapse(getElapse());
	}

	public TimeMeter printElapse() {
		printElapse("耗时:{}");
		return this;
	}

	public TimeMeter printElapse(String pattern) {
		esdk.sout(EasyStr.format(pattern,esdk.time.formatElapse(getElapse())));
		return this;
	}

	public static TimeMeter startNew(){
		return new TimeMeter();
	}

	@Override public String toString() {
		return getElapse("耗费时间:{}");
	}

	public static void main(String[] args) {
		new TimeMeter().end().printElapse("首次加载比较慢，耗时:{}");
		esdk.tool.assertEquals(new TimeMeter().end().printElapse().getElapse()<=1);
		TimeMeter sw=new TimeMeter();
		esdk.tool.sleep(1000);
		esdk.sout("耗时:{}ms",sw.getElapse());
		esdk.sout("耗时:{}",sw.getHumanElapse());
		sw.printElapse();
	}
}
